<template>
  <div class="rf-upload-file">
    <el-upload
      ref="upload"
      class="upload"
      :action="url"
      :on-success="handleMoreSuccess"
      :on-preview="handlePreview"
      :on-exceed="handleExceed"
      :on-remove="handleRemove"
      :on-error="handleError"
      :before-upload="handleBeforeUpload"
      :file-list="fileList"
      :auto-upload="autoUpload"
      :limit="limit"
      :data="params"
    >
      <el-button
        slot="trigger"
        :size="size"
        type="primary"
      >{{ btnText }}</el-button>
      <el-button
        v-if="!autoUpload"
        style="margin-left: 10px;"
        :size="size"
        type="success"
        @click="submitUpload"
      >上传到服务器</el-button>
      <span
        v-if="tip"
        slot="tip"
        class="el-upload__tip"
      >{{ tip }}</span>
    </el-upload>
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import Cookies from 'js-cookie'
import api from '@/utils/api.js'
export default {
  name: 'RfUploadFile',
  props: {
    limit: {
      type: [String, Number],
      default: 10
    },
    autoUpload: {
      type: Boolean,
      default: false
    },
    tip: {
      type: String,
      default: ''
    },
    btnText: {
      type: String,
      default: '选择文件'
    },
    url: {
      type: String,
      default: api.uploadFileUrl()
    },
    needValid: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [],
      params: {
        access_token: ''
      }
    }
  },
  computed: {
    ...mapGetters(['size'])
  },
  mounted() {
    this.params.access_token = Cookies.get('lms_token')
  },
  methods: {
    handleBeforeUpload(file) {
      const name = file.name.toLowerCase()
      if (this.needValid) {
        const filter = /\.(png|jpg|mp4|mp3|xls|xlsx|ppt|pptx|pdf|doc|docx|zip)$/i;
        if (!filter.test(name)) {
          this.$message.error('不支持此种类型素材的上传，请重新上传');
          this.clearFiles()
          return false;
        }
      }
    },
    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      this.$emit('remove', fileList)
    },
    handlePreview(file) {

    },
    handleExceed() {
      this.$message.warning(this.$t('TIP.UPLOAD_LIMIT', { limit: this.limit }))
    },
    // 上传成功操作
    handleMoreSuccess(response, file, fileList) {
      if (response.resp_code !== 200) {
        this.$message.error(this.$t('TIP.UPLOAD_ERROR'))
        this.clearFiles()
        return
      }
      if (!this.autoUpload) this.clearFiles()
      this.$emit('cb', response.data, fileList)
    },
    // 文件上传失败提示
    handleError(err, flie, flieList) {
      this.$message.error(this.$t('TIP.UPLOAD_ERROR'))
    },
    setFileList(data) {
      this.fileList = data
    },
    clearFiles() {
      this.$refs.upload.clearFiles()
    }
  }
}
</script>
<style lang="scss">
  .el-upload__tip {
    display: block
  }
</style>
